package Data;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import Domain.Seller;
import Main.Constants;

public class SellerMapper {


	public Seller insert(Seller s) throws SQLException, ClassNotFoundException {
		String query = Constants.INSERT_SELLER;
		Statement stmt = Database.createStatement();

		query = query.replaceAll("::name", "" + s.getName());
		query = query.replaceAll("::email", "" + s.getEmail());
		query = query.replaceAll("::phonenr", "" + s.getPhonenr());

		System.out.println("Calling database:" + query);
		stmt.execute(query, Statement.RETURN_GENERATED_KEYS);
		ResultSet rs = stmt.getGeneratedKeys();
		rs.next();
		int generatedId = rs.getInt(1);
		System.out.println("New primary key was generated: " + generatedId);
		s.setId(generatedId);

		return s;
	}

	/**
	 * Retrieves the seller with given primary key.
	 * 
	 * @param id
	 *            an integer that is matches against the primary key field 'id'
	 *            in the database.
	 * @return a {@link domain.Product} object that represents the product with
	 *         given id value in the database.
	 * @throws SQLException
	 *             when the SQL statement cannot be executed.
	 * @throws ClassNotFoundException
	 *             when there is something wrong with the database driver.
	 */
	public Seller retrieve(int id) throws SQLException, ClassNotFoundException {
		Statement stmt = Database.createStatement();
		String selectString = Constants.SELECT_SELLER;
		selectString = selectString.replaceAll("::id_seller", "" + id);
		System.out.println("Calling database for a product: " + selectString);
		ResultSet rs = stmt.executeQuery(selectString);
		if (rs.next()) {
			Seller seller = new Seller();
			seller.setId(id);
			seller.setName(rs.getString(1));
			seller.setEmail(rs.getString(2));
			seller.setPhonenr(rs.getString(3));
			return seller;
		} else {
			return null;
		}
	}
}
